// src/stores/sysUser.js
import { defineStore } from 'pinia'
import {
  listAllSysUsersAPI,
  addSysUserAPI,
  updateSysUserAPI,
  deleteSysUserAPI,
  getSysUserByIdAPI,
  toggleUserStatusAPI,
  assignRoleAPI,
  unassignRoleAPI,
  searchByUserNameAPI
} from '@/api/sysUserAPI'
import { listAllNoPageAPI} from '@/api/sysUserAPI'
export const useSysUserStore = defineStore('sysUser', {
  state: () => ({
    users: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    loading: false,
    selectedUser: null,
    userInfo: null
  }),

  actions: {
    // 获取所有用户（带分页）
    async fetchUsers(page = 1, size = 10) {
      this.loading = true
      try {
        const res = await listAllSysUsersAPI({
          pageNo: page,
          pageSize: size
        })

        // 修改判断条件以适配后端返回的 code: 0 表示成功
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          // 处理 MyBatis Plus 分页返回的数据结构
          // 后端返回的是 Page<SysUserVO> 对象，包含 records 和 total 字段
          if (res.data && Array.isArray(res.data.records)) {
            this.users = res.data.records
            this.total = res.data.total || 0
          } else {
            // 如果没有 records 字段或不是数组，则初始化为空
            this.users = []
            this.total = 0
          }

          this.currentPage = page
          this.pageSize = size
        } else {
          console.error('获取用户列表失败:', res?.message || '未知错误')
          this.users = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取用户失败:', error)
        this.users = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 根据用户名搜索用户
    async searchUsersByUsername(username, page = 1, size = 10) {
      this.loading = true
      try {
        const res = await searchByUserNameAPI({
          userName: username || undefined
        })

        if (res && (res.code === 0 || res.code === 200) && res.data) {
          // 处理返回的数据
          if (Array.isArray(res.data)) {
            this.users = res.data
            this.total = res.data.length
          } else {
            this.users = []
            this.total = 0
          }

          this.currentPage = page
          this.pageSize = size
        } else {
          console.error('搜索用户失败:', res?.message || '未知错误')
          this.users = []
          this.total = 0
        }
      } catch (error) {
        console.error('搜索用户失败:', error)
        this.users = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 新增用户
    async addUser(userData) {
      try {
        const res = await addSysUserAPI(userData)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchUsers(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '添加用户失败')
        }
      } catch (error) {
        console.error('新增用户失败:', error)
        throw error
      }
    },

    // 编辑用户
    async updateUser(id, userData) {
      try {
        const res = await updateSysUserAPI({
          id: id,
          saveBO: userData
        })

        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchUsers(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '更新用户失败')
        }
      } catch (error) {
        console.error('更新用户失败:', error)
        throw error
      }
    },

    // 删除用户
    async deleteUser(id) {
      try {
        const res = await deleteSysUserAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchUsers(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '删除用户失败')
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        throw error
      }
    },

    // 获取单个用户详情
    async getUserById(id) {
      try {
        const res = await getSysUserByIdAPI(id)
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          this.selectedUser = res.data
          return res.data
        } else {
          throw new Error(res?.message || '获取用户详情失败')
        }
      } catch (error) {
        console.error('获取用户详情失败:', error)
        throw error
      }
    },

    // 切换用户状态
    async toggleUserStatus(id) {
      try {
        const res = await toggleUserStatusAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchUsers(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '切换用户状态失败')
        }
      } catch (error) {
        console.error('切换用户状态失败:', error)
        throw error
      }
    },

    async getRoles() {
      try {
        const res = await listAllNoPageAPI()
        if (res && res.code === 0 && Array.isArray(res.data)) {
          return res.data
        } else {
          throw new Error(res?.msg || '获取角色失败')
        }
      } catch (error) {
        console.error('获取角色列表失败:', error)
        throw error
      }
    },

    async assignRole(userId, roleId) {
      try {
        const res = await assignRoleAPI(userId, roleId)
        if (res && (res.code === 0 || res.code === 200)) {
          return { success: true }
        } else {
          throw new Error(res?.message || '分配角色失败')
        }
      } catch (error) {
        console.error('分配角色失败:', error)
        throw error
      }
    },

    async unassignRole(userId, roleId) {
      try {
        const res = await unassignRoleAPI(userId, roleId)
        if (res && (res.code === 0 || res.code === 200)) {
          return { success: true }
        } else {
          throw new Error(res?.message || '解除角色失败')
        }
      } catch (error) {
        console.error('解除角色失败:', error)
        throw error
      }
    },
    
    clearUserInfo() {
      this.userInfo = null;
    }
  }
})